import audioManager from '../../general/audioManager'
import GamePanel from '../../hall/gamePanel'
const { ccclass, property } = cc._decorator
@ccclass
export class game816 extends cc.Component {
  @property(cc.Label)
  score_label: cc.Label = null
  @property(cc.Label)
  max_label: cc.Label = null
  @property(cc.Node)
  frame_node: cc.Node = null
  @property(cc.Node)
  heng_pre: cc.Node = null
  @property(cc.Node)
  bar_pre: cc.Node = null
  @property(cc.Node)
  content_node: cc.Node = null
  @property(cc.AudioClip)
  mp3: cc.AudioClip[] = []
  isFire: number = 0
  isGameOver: boolean = false
  isTouchEnd: boolean = false
  currentNode: cc.Node = null
  currentIndex = 1
  onLoad() {
    this.initData()
  }
  /**初始化数据 */
  initData() {
    cc.director.getPhysicsManager().enabled = true

    this.max_label.string = '0'
    this.score_label.string = '0'
    this.node.on(cc.Node.EventType.TOUCH_START, this.tochStart, this)
    this.node.on('checkGameOver', this.checkGameOver, this)
    this.node.on('onhit', this.onhit, this)
    this.creatOneBar()
  }
  onhit(type) {
    audioManager.playEffect(this.mp3[0])
    if (type) {
      this.content_node.children.forEach((v) => v.runAction(cc.moveBy(0.3, 0, -180)))
      this.scheduleOnce(() => {
        const result = this.content_node.children.find((v) => v.convertToWorldSpaceAR(cc.v2(0, 0)).y > -50)
        if (result) {
          this.content_node.children.forEach((v) => (v.getComponent(cc.RigidBody).type = cc.RigidBodyType.Static))
          this.updateScore(10)
          this.currentNode = null
          this.creatOneBar()
          this.isTouchEnd = false
        } else {
          this.checkGameOver()
        }
      }, 0.35)
    } else {
      this.currentNode = null
      this.creatOneBar()
      this.isTouchEnd = false
    }
  }
  updateScore(score) {
    GamePanel.instance.updateScore(score)
  }
  checkGameOver() {
    if (this.isGameOver) {
      return
    }
    this.isGameOver = true
    this.schedule(
      () => {
        GamePanel.instance.showGameStatis()
      },
      1,
      0
    )
  }
  /**触摸发射 */
  tochStart(event: cc.Event.EventTouch) {
    if (this.isTouchEnd) {
      return
    }
    this.isTouchEnd = true
    this.currentNode.stopAllActions()
    this.scheduleOnce(() => {
      if (this.currentNode) {
        this.currentNode.getComponent(cc.RigidBody).type = cc.RigidBodyType.Dynamic
      }
    })
  }
  creatOneBar() {
    if (this.currentIndex % 3 == 0) {
      const pre = cc.instantiate(this.heng_pre)
      this.content_node.addChild(pre)
      pre.active = true
      pre.x = -520
      pre.y = 260
      pre['type'] = 1
      this.currentNode = pre
    } else {
      const pre = cc.instantiate(this.bar_pre)
      this.content_node.addChild(pre)
      pre.active = true
      pre.x = -500
      pre.y = 260
      pre['type'] = 0
      this.currentNode = pre
    }
    this.currentIndex++
  }
}
